package Utils.db;

import Utils.UtilUtils;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * DBCP工具类
 * @author d11yu
 */
public class DruidUtils {
    private static DruidDataSource dds = null;
    private static volatile DruidUtils instance = null;
    private static ThreadLocal<Connection> tlConn = new ThreadLocal<>();

    /**
     * 构造函数
     *
     * @param path 配置文件路径
     */
    private DruidUtils(String path) {
        try {
            dds = (DruidDataSource) DruidDataSourceFactory.createDataSource(UtilUtils.loadProperties(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取实例，如果未实例化，则返回null。
     *
     * @return
     */
    public static DruidUtils getInstance() {
        return instance;
    }

    /**
     * 获取实例，应首先调用此方法。
     *
     * @param path 配置文件路径
     * @return
     */
    public static DruidUtils getInstance(String path){
        if (instance == null) {
            synchronized (DruidUtils.class) {
                if (instance == null) {
                    instance = new DruidUtils(path);
                }
            }
        }
        return instance;
    }

    /**
     * 返回DruidDataSource
     *
     * @return
     */
    public DruidDataSource getDds() {
        return dds;
    }

    /**
     * 获取SQL Connection，如果获取失败，则返回null。
     *
     * @return
     * @throws SQLException
     */
    public Connection getConnection(){
        return getConnection(true);
    }

    /**
     * 获取SQL Connection，如果获取失败，则返回null。
     *
     * @param isAutoCommit 是否自动提交，默认为true。如需使用事务，请传入false。
     * @return
     */
    public Connection getConnection(boolean isAutoCommit){
        Connection conn = tlConn.get();
        if (conn == null) {
            try {
                conn = dds.getConnection();
                conn.setAutoCommit(isAutoCommit);
                tlConn.set(conn);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return conn;
    }

    /**
     * close connection
     */
    public void close() {
        JdbcUtilsStatic.close(tlConn);
    }

    /**
     * commit and close connection
     */
    public void commitAndClose() {
        JdbcUtilsStatic.commitAncClose(tlConn);
    }

    /**
     * rollback and close connection
     */
    public void rollbackAndClose() {
        JdbcUtilsStatic.rollbackAncClose(tlConn);
    }
}
